from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from settings import TOKEN_EXPIRE, SECRET_KEY
from errors import TokenError


def create_token(playload):
    """
    创建token
    """
    s = Serializer(SECRET_KEY, expires_in=TOKEN_EXPIRE)
    token = s.dumps(playload).decode("ascii")
    return token


def token_decode(token):
    """
    解码token
    """
    s = Serializer(SECRET_KEY)
    try:
        payload = s.loads(token)
    except Exception:
        raise TokenError("无效token或登录过期")
    return payload


def generate_reset_token(username, expires_sec=60 * 30):
    """
    生成重置密码token
    """
    s = Serializer(SECRET_KEY, expires_in=expires_sec)
    token = s.dumps({"username": username}).decode("utf-8")
    return token


def verify_reset_token(token):
    """
    验证重置密码token
    """
    s = Serializer(SECRET_KEY)
    try:
        username = s.loads(token)["username"]
    except Exception:
        raise Exception("验证token错误")
    return username
